<style>
body {
  background-image: url("../views/img/loginAndReg.jpg");
  margin: 0;
  background-size: cover;
  background-repeat: no-repeat;
}

a:link {
  color: #606266;
}

a:visited {
  color: #606266;
}

a:active {
  color: #606266;
}

.el-checkbox__label {
  padding-left: 5px;
}

/*图形验证码开始*/
.input-val {
  width: 130px;
  height: 40px;
  border: 0;
  box-sizing: border-box;
}

#canvas {
  vertical-align: middle;
  box-sizing: border-box;
  border: 1px solid #ddd;
  cursor: pointer;
  width: 95px;
  height: 40px;

}

/*图形验证码结束*/

</style>

<template>
  <div id="app">
    <el-card style="border: 0; width: 300px; height: auto; margin: 170px auto 0;
            background-color: rgba(255,255,255,0.3); position: relative; padding: 0px">
      <h1 style="margin: 13.4px 0; font-size: 20px; color: green; text-align: center">
        社区疫情防控中心登录</h1>

      <!--用户名表单-->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm"
               class="demo-ruleForm" v-if="isVisible"
               style="width: 230px; margin: 0 0 0 15px">

        <!--用户名-->
        <i class="el-icon-user-solid" style="font-size: 25px;
                position: absolute; top: 80px; left: 10px"></i>
        <el-form-item prop="userName">
          <el-input autocomplete="off" clearable v-model="ruleForm.userName"
                    prefix-icon="el-icon-user"
                    type="text" name="userName" placeholder="请输入用户名或手机号"
                    style="box-sizing: border-box"></el-input>
        </el-form-item>

        <!--密码-->
        <i class="el-icon-lock" style="font-size: 25px; position: absolute; top: 143px; left: 10px"></i>
        <el-form-item prop="userPassword">
          <el-input autocomplete="off" show-password v-model="ruleForm.userPassword"
                    prefix-icon="el-icon-lock" type="password"
                    placeholder="请输入密码"></el-input>
        </el-form-item>

        <!--图形验证-->
        <i class="el-icon-warning-outline" style="font-size: 25px;
             position: absolute; top: 204px; left: 10px"></i>
        <div class="code" style="padding: 0">
          <el-input prefix-icon="el-icon-warning-outline" type="text" v-model="code"
                    placeholder="请输入验证码"
                    class="input-val"></el-input>
          <canvas id="canvas"></canvas>
        </div>

        <!--保存账号密码、忘记密码-->
        <el-form-item style=" margin: 0; position: relative; top: -5px; left: 5px">
          <el-checkbox v-model="ruleForm.userRem">保存密码</el-checkbox>
          <a href="/forgotPass"
             style="font-size: 14px; text-decoration: none; position: relative; left: 75px">忘记密码？</a>
        </el-form-item>

        <!--用户登录-->
        <el-form-item style="margin:-7px 0 0 0">
          <el-button style="font-size: 16px; margin-left: 2px; width: 225px;border: 0px;border-radius: 30px;
                height: 40px; color: black" type="success" @click="userLogin('ruleForm')">登录
          </el-button>
        </el-form-item>

        <!--注册-->
        <el-row style="text-align: center; margin-top: 10px;">
          <el-button style="font-size: 16px; border-radius: 30px; width: 225px; color: black"
                     type="success" @click="reg()">新用户注册
          </el-button>
        </el-row>
      </el-form>

      <!--管理员表单-->
      <el-form :model="ruleForm1" :rules="rules" ref="ruleForm1"
               class="demo-ruleForm1" v-else style="width: 230px; margin: 0 0 0 15px">
        <!--账号-->
        <i class="el-icon-user-solid" style="font-size: 25px;
             position: absolute; top: 80px; left: 10px"></i>
        <el-form-item prop="admName">
          <el-input clearable v-model="ruleForm1.admName" prefix-icon="el-icon-user"
                    type="text" placeholder="请输入管理员账号"
                    style="box-sizing: border-box"></el-input>
        </el-form-item>

        <!--密码-->
        <i class="el-icon-lock" style=" font-size: 25px; position: absolute; top: 143px; left: 10px"></i>
        <el-form-item prop="admPassword">
          <el-input show-password v-model="ruleForm1.admPassword" prefix-icon="el-icon-lock"
                    type="password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <!--保存密码-->
        <el-form-item style="margin: 0; position: relative; top: -16px; left: 73px">
          <el-checkbox v-model="ruleForm1.admRem">保存密码</el-checkbox>
        </el-form-item>

        <!--登录-->
        <el-form-item style="margin:-11px 0 0 0">
          <el-button @click="admLogin()" type="success" style="font-size: 16px;
                 margin-left: 2px; width: 225px; color: black;
                 border-radius: 30px;border: 0;height: 40px">管理员登录
          </el-button>
        </el-form-item>
      </el-form>

      <div style="position: relative; top: 4px; left: 38px">
        <input disabled type="radio" name="job" :checked="isVisible==true?true:false"
               style="margin-left: 26px;">
        <el-button @click="user()" type="text">用户</el-button>

        <input disabled type="radio" name="job" :checked="isVisible==false?true:false"
               style="color: black;margin-left: 10px">
        <el-button @click="adm()" type="text">管理员</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    /*.................................图 形 验 证 码 开 始.......................................*/
    $(function () {
      var show_num = [];
      draw(show_num);
      this.show_num = show_num;
      localStorage.setItem("num", JSON.stringify(this.show_num.join('')));

      $("#canvas").on('click', function () {
        draw(show_num);
        localStorage.setItem("num", JSON.stringify(show_num.join('')));
      })
    })

    //生成并渲染出验证码图形
    function draw(show_num) {
      var canvas_width = $('#canvas').width();
      var canvas_height = $('#canvas').height();
      var canvas = document.getElementById("canvas");//获取到canvas的对象，演员
      var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      var sCode = "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      var aCode = sCode.split(",");
      var aLength = aCode.length;//获取到数组的长度

      for (var i = 0; i < 4; i++) {  //这里的for循环可以控制验证码位数（如果想显示6位数，4改成6即可）
        var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
        // var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
        var deg = Math.random() - 0.5; //产生一个随机弧度
        var txt = aCode[j];//得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        var x = 10 + i * 20;//文字在canvas上的x坐标
        var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";
        context.translate(x, y);
        context.rotate(deg);
        context.fillStyle = randomColor();
        context.fillText(txt, 0, 0);
        context.rotate(-deg);
        context.translate(-x, -y);
      }
      for (var i = 0; i <= 5; i++) { //验证码上显示线条
        context.strokeStyle = randomColor();
        context.beginPath();
        context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.stroke();
      }
      for (var i = 0; i <= 30; i++) { //验证码上显示小点
        context.strokeStyle = randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }
    }

    //得到随机的颜色值
    function randomColor() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    }

    /*..................................图 形 验 证 码 结 束........................................*/

    return {
      code: "",
      num: '',
      show_num: [],
      isVisible: true,
      ruleForm: {
        userName: "",
        userPassword: "",
        userRem: false
      },
      ruleForm1: {
        admName: "",
        admPassword: "",
        admRem: false
      },

      rules: {
        userName: [
          {required: true, message: '请输入用户名或手机号', trigger: 'blur'}
        ],
        userPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
        admName: [
          {required: true, message: '请输入管理员账号', trigger: 'blur'},
        ],
        admPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    reg() {
      this.$router.push('/reg');
    },
    userLogin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let num = localStorage.getItem("num");
          let code = this.code.toLowerCase();
          let code1 = JSON.stringify(code);
          if (code1 === "") {
            this.$message.error("请先完成图形验证！!");
            return;
          } else if (code1 !== num) {
            this.$message.error("验证码错误！请重新输入！");
            return;
          }

          let url = 'http://localhost:8080/user/login'
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ', formData);

          this.axios.post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state === 20000) {
              this.$notify.success({
                message: '登录成功！',
                type: 'success',
                position: "top-left"
              });
              let userJwt = responseBody.data;
              console.log('登录成功，userJwt=' + userJwt);
              localStorage.setItem("userJwt", userJwt);
              location.href = 'http://localhost:9000/user';
            } else {
              this.$notify.error({
                message: responseBody.message,
                type: 'error',
                position: "top-right"
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    admLogin() {
      let url = 'http://localhost:8081/admin/login';
      let formData = this.qs.stringify(this.ruleForm1);
      console.log('formData = ', formData);
      this.axios.post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          let adminJwt = responseBody.data;
          console.log('登录成功，JWT = ' + adminJwt);
          localStorage.setItem('adminJwt', adminJwt);
          this.$router.push('/');
          this.$notify.success({
            title: '提示',
            message: '登录成功！',
            showClose: true,
            position: 'top-right'
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },
    user() {
      this.isVisible = true;
      location.reload();
    },
    adm() {
      this.isVisible = false;
    },
    cookie() {
      //取出cookie里面的数据 显示到页面中
      let arr = document.cookie.split(";");
      console.log("cookie数据是：" + arr);
      for (let cookie of arr) {
        let cookieArr = cookie.split("=");
        let name = cookieArr[0].trim();
        let value = cookieArr[1];
        console.log("name是" + name);
        console.log("value是" + value);
        if (name === "userName") {
          this.ruleForm.userName = value;
        } else if (name === "userPassword") {
          this.ruleForm.userPassword = value;
        } else if (name === "admName") {
          this.ruleForm1.admName = value;
        } else if (name === "admPassword") {
          this.ruleForm1.admPassword = value;
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },

  mounted() {
    this.cookie();
  },
}
</script>
